package cn.zyq.charging.order.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息的生产者(发送MQTT消息的工具类)：
 * 用来给MQTT发送消息(MqttProducer在此模块中的作用：
 *   让订单模块给充电桩发送开始充电的消息 topic是"/topic/start/+充电桩id"message是ChargingInfoDTO(gunId,pileId,orderNo，msg)
 *   <订单模块发送消息给MQTT服务器，充电桩订阅MQTT服务器的某个topic的消息来接收此消息>)
 * 此类因为不用接受消息(只是发送消息)， 所以不需要实现MqttCallbackExtended接口，及实现四个方法：
 *   connectComplete()、connectionLost()、messageArrived()、deliveryComplete()
 */
@Slf4j
@Component
public class MqttProducer{//MQTT: 是消息队列传输协议

    @Autowired//因为要在MqttConfig配置类中new MqttConsumer的对象，所以无法注入(就改成下边构造方法注入的方式)
    private MqttClient mqttClient;

    /*public void setMqttClient(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }*/

    //public MqttConsumer(){}
    public MqttProducer(MqttClient mqttClient){
        this.mqttClient=mqttClient;
    }

    /**给MQTT消息中间件EMQX发送消息*/
    public void sendMessage(String topic,String msg) {
        try {
            log.debug("发送消息到EQMX, topic:{}, message:{}", topic, msg);
            mqttClient.publish(topic, msg.getBytes(),0,false);
            log.debug("发送消息到EQMX, topic:{}, message:{}成功", topic, msg);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }
}
